<template>
  <div class="hello">
    <div id="cesiumContainer"></div>
    <ul class="contralPanel">
      <li>
        <button @click="drawPoint">画点</button>
      </li>
      <li>
        <button @click="drawLine">画线</button>
      </li>
    </ul>
    <div></div>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      viewer: "",
      czml: [
        {
          id: "document",
          name: "CZML Geometries:Polyline",
          verison: "1.0"
        },
        {
          id: "redLine",
          name: "Red line on the surface",
          polyline: {
            positions: {
              cartographicDegrees: [-75, 35, 0, -125, 35, 0]
            },
            material: {
              solidColor: {
                color: {
                  rgba: [255, 0, 0, 255]
                }
              }
            },
            width: 5
          }
        }
      ],
      pointPositions: "",
      linePositions: ""
    };
  },
  mounted() {
    // 显示地球
    this.viewer = new Cesium.Viewer("cesiumContainer");
    // 设置默认Imagery图层为Mapbox Streets
    this.viewer.baseLayerPicker.viewModel.selectedImagery = this.viewer.baseLayerPicker.viewModel.imageryProviderViewModels[4];
    this.showPoint();
    // this.showLine();
  },
  methods: {
    // 显示点
    showPoint() {
      this.viewer.entities.add({
        position: this.pointPositions,
        point: {
          pixelSize: 5,
          color: Cesium.Color.YELLOW
        }
      });
    },
    // 画点
    drawPoint() {
      var _this = this;
      var scene = this.viewer.scene;
      var entity = this.viewer.entities.add({
        label: {
          showBackground: true,
          font: "50px monospace",
          // horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
          // verticalOrigin: Cesium.VerticalOrigin.TOP,
          pixelOffset: new Cesium.Cartesian2(15, 0)
        },
        point: {
          pixelSize: 5,
          color: Cesium.Color.RED
        }
      });

      // Mouse over the globe to see the cartographic position
      var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
      handler.setInputAction(function(movement) {
        console.log("平面坐标系", movement.position);
        var cartesian = _this.viewer.camera.pickEllipsoid(
          movement.position,
          scene.globe.ellipsoid
        );
        var cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        var longitudeString = Cesium.Math.toDegrees(
          cartographic.longitude
        ).toFixed(2);
        var latitudeString = Cesium.Math.toDegrees(
          cartographic.latitude
        ).toFixed(2);
        console.log("cartographic", cartographic);
        console.log("cartesian", cartesian);
        // entity.position = cartesian;
        // positions.push(cartesian);
        _this.pointPositions = cartesian;
        _this.showPoint();
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      // 单击鼠标右键结束画点
      handler.setInputAction(function(movement) {
        handler.destroy();
      }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
    },
    // 显示线
    showLine() {
      var _this = this;

      /** 
      // 处理positions数据
      var newPosition_WGS84 = [];
      var nowPolylinePsition = [];
      for (let i = 0; i < this.linePositions.length; i++) {
        let everyPoint_WGS84 = this.Cartesian3_to_WGS84({
          // 把每个点的坐标转成WGS84
          x: this.linePositions[i].x,
          y: this.linePositions[i].y,
          z: this.linePositions[i].z
        });
        newPosition_WGS84.push(everyPoint_WGS84);
      }
      this.linePositions.forEach(e => {
        nowPolylinePsition.push(e.x);
        nowPolylinePsition.push(e.y);
        nowPolylinePsition.push(e.z);

      });


        */
      this.viewer.entities.add({
        name: "Red line on the surface",
        polyline: {
          positions: _this.linePositions,
          width: 5,
          material: Cesium.Color.ORANGE
        }
      });
      this.viewer.zoomTo(this.viewer.entities);
    },
    // 画线
    drawLine() {
      var _this = this;

      var PolyLinePrimitive = (function() {
        // 显示线
        function realTime(positions) {
          this.options = {
            id: "lineEntity",
            polyline: {
              show: true,
              positions: [],
              material: Cesium.Color.RED,
              width: 3
            }
          };
          console.log("this.positions", this);

          this.positions = positions;
          this._init();
        }
        // 实时刷新
        realTime.prototype._init = function() {
          var _self = this;
          var _update = function() {
            return _self.positions;
          };
          //实时更新polyline.positions
          this.options.polyline.positions = new Cesium.CallbackProperty(
            _update,
            false
          );
          _this.viewer.entities.add(this.options);
        };
        return realTime;
      })();

      var scene = this.viewer.scene;
      var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
      var positions = [];
      var poly = undefined;
      //鼠标左键单击画点
      handler.setInputAction(function(movement) {
        var cartesian = _this.viewer.scene.camera.pickEllipsoid(
          movement.position,
          _this.viewer.scene.globe.ellipsoid
        );
        if (positions.length == 0) {
          positions.push(cartesian.clone());
        }
        positions.push(cartesian);
        console.log("positions", positions);
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
      //鼠标移动事件
      handler.setInputAction(function(movement) {
        var cartesian = _this.viewer.scene.camera.pickEllipsoid(
          movement.endPosition,
          _this.viewer.scene.globe.ellipsoid
        );
        if (positions.length >= 2) {
          if (!Cesium.defined(poly)) {
            poly = new PolyLinePrimitive(positions);
          } else {
            if (cartesian != undefined) {
              positions.pop();
              cartesian.y += 1 + Math.random();
              positions.push(cartesian);
            }
          }
        }
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

      //单击鼠标右键结束画线
      handler.setInputAction(function(movement) {
        handler.destroy();
        _this.linePositions = positions;
        _this.viewer.entities.remove(
          _this.viewer.entities.getById("lineEntity")
        );
        _this.showLine();
      }, Cesium.ScreenSpaceEventType.RIGHT_CLICK);
    },

    // 笛卡尔坐标系转WGS84坐标系
    Cartesian3_to_WGS84(point) {
      var cartesian33 = new Cesium.Cartesian3(point.x, point.y, point.z);
      var cartographic = Cesium.Cartographic.fromCartesian(cartesian33);
      var lat = Cesium.Math.toDegrees(cartographic.latitude);
      var lng = Cesium.Math.toDegrees(cartographic.longitude);
      var alt = cartographic.height;
      return { lat: lat, lng: lng, alt: alt };
    }
  },
  components: {}
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1,
h2 {
  font-weight: normal;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
.contralPanel {
  position: fixed;
  top: 0;
  left: 0;
}
</style>
